package com.mdd.maduoduo.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.maning.updatelibrary.InstallUtils;
import com.mdd.maduoduo.BuildConfig;
import com.mdd.maduoduo.MyApplication;
import com.mdd.maduoduo.R;
import com.mdd.maduoduo.constants.CommonConstants;
import com.mdd.maduoduo.di.component.DaggerUIComponent;
import com.mdd.maduoduo.di.component.UIComponent;
import com.mdd.maduoduo.entity.BannerEntity;
import com.mdd.maduoduo.entity.CheckVersionEntity;
import com.mdd.maduoduo.entity.LogoutEvent;
import com.mdd.maduoduo.event.WxLoginEvent;
import com.mdd.maduoduo.fragment.HomeFragment;
import com.mdd.maduoduo.fragment.MineFragment;
import com.mdd.maduoduo.presenter.LoginPresenter;
import com.mdd.maduoduo.utils.AlertUtils;
import com.mdd.maduoduo.utils.AppManager;
import com.mdd.maduoduo.utils.GlideUtils;
import com.mdd.maduoduo.utils.KeepAliveService;
import com.mdd.maduoduo.utils.MuPermission;
import com.mdd.maduoduo.utils.OnPermissionListener;
import com.mdd.maduoduo.utils.RxBus;
import com.mdd.maduoduo.utils.SmsUploadService;
import com.mdd.maduoduo.utils.SpUtils;
import com.mdd.maduoduo.utils.ToastUtils;
import com.mdd.maduoduo.utils.Utils;
import com.mdd.maduoduo.view.interfaces.CheckVersionView;
import com.mdd.maduoduo.view.interfaces.GetBannerView;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;

@RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
public class MainActivity extends BaseActivity implements GetBannerView, CheckVersionView {

    private MineFragment mineFragment;

    private HomeFragment homeFragment;

    private FragmentManager mFragmentManager;

    private RadioButton main_home_btn, main_mine_btn;

    private MuPermission muPermission;

    private ImageView ivItem;

    private TextView tvItem;

    @Inject
    public LoginPresenter mPresenter;

    private LinearLayout llItem;

    private String[]permission = {Manifest.permission.READ_SMS,Manifest.permission.RECEIVE_SMS,Manifest.permission.POST_NOTIFICATIONS,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.REQUEST_INSTALL_PACKAGES};

    private CompositeDisposable disposables = new CompositeDisposable();

    private boolean isClose = true;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    protected void initializeInjector() {
        super.initializeInjector();
        mPresenter = new LoginPresenter();
        UIComponent uiComponent = DaggerUIComponent.builder().applicationComponent(getApplicationComponent())
                .activityModule(getActivityModule()).build();
        uiComponent.inject(this);
        mPresenter.setGetBannerView(this);
        mPresenter.setCheckVersionView(this);
    }

    @Override
    protected void initView() {
        super.initView();
        muPermission = new MuPermission(this);
        mFragmentManager = getSupportFragmentManager();
        main_home_btn = findViewById(R.id.main_home_btn);
        main_mine_btn = findViewById(R.id.main_mine_btn);
        ivItem = findViewById(R.id.ivItem);
        tvItem = findViewById(R.id.tvItem);
        llItem = findViewById(R.id.llItem);

        homeFragment = new HomeFragment();
        mineFragment = new MineFragment();
        switchFragment(homeFragment, "HomeFragment");
        main_home_btn.setChecked(true);

        disposables.add(
                RxBus.getInstance().toObservable(LogoutEvent.class)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(event -> {
                            if (isClose){
                                isClose = false;
                                ToastUtils.showLongToast(MainActivity.this,event.msg);
                                SpUtils.put(MainActivity.this, CommonConstants.TOKEN,"");
                                finish();
                                startActivity(new Intent(MainActivity.this,LoginActivity.class));
                            }
                        })
        );

        muPermission.requestPermission(permission, 1000, new OnPermissionListener() {
            @Override
            public void onPermissionGranted() {

            }

            @Override
            public void onPermissionDenied() {

            }
        });
        //检查更新
        mPresenter.checkVersion(BuildConfig.VERSION_NAME);

        mPresenter.getBannerList("2004");
        startServices();

    }

    private void startServices() {
        // 启动上传服务
        Intent uploadIntent = new Intent(this, SmsUploadService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(uploadIntent);
        } else {
            startService(uploadIntent);
        }

        // 启动保活服务
        Intent keepAliveIntent = new Intent(this, KeepAliveService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(keepAliveIntent);
        } else {
            startService(keepAliveIntent);
        }
    }

    @Override
    protected void onClick() {
        main_home_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchFragment(homeFragment, "HomeFragment");
            }
        });

        main_mine_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchFragment(mineFragment, "MineFragment");
            }
        });
    }

    protected Fragment switchFragment(Fragment to, String tag) {
        if (mContent != to) {
            FragmentTransaction transaction = mFragmentManager.beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                transaction.hide(mContent).add(R.id.replace_layout, to, tag).commitAllowingStateLoss(); //
                // 隐藏当前的fragment，add下一个到Activi  ty中
            } else {
                transaction.hide(mContent).show(to).commitAllowingStateLoss(); //
                // 隐藏当前的fragment，显示下一个
            }
            mContent = to;
        }
        return mContent;
    }

    @Override
    public void renderBannerSuccess(BannerEntity bannerEntity) {
        if (bannerEntity.data!=null){
            if (bannerEntity.data.functionConfigDtos!=null){
                if (!bannerEntity.data.functionConfigDtos.get(0).itemDtos.isEmpty()){
                    GlideUtils.getInstances().loadNormalImg(this,ivItem,bannerEntity.data.functionConfigDtos.get(0).itemDtos.get(0).url);
                    tvItem.setText(bannerEntity.data.functionConfigDtos.get(0).itemDtos.get(0).functionName);
                    llItem.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Utils.jumpOther(MainActivity.this,bannerEntity.data.functionConfigDtos.get(0).itemDtos.get(0));
                        }
                    });
                }
            }
        }

    }
    private ProgressDialog mainPDialog;

    private AlertDialog mShow;

    private int mainPrs;
    @Override
    public void renderCheckSuccess(CheckVersionEntity checkVersion) {
        if (checkVersion.code.equals("200")){
            if (checkVersion.data.checkResult!=0){
                AlertUtils.showUpdateAlert(MainActivity.this, checkVersion, new AlertUtils.DownloadListener() {
                    @Override
                    public void sureSelect(String url) {
                        mainPDialog = new ProgressDialog(MainActivity.this);

                        // 设置进度条风格，风格为长形
                        mainPDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

                        // 设置ProgressDialog 标题
                        mainPDialog.setTitle(MyApplication.getInstance().getString(R.string.app_name));

                        // 设置ProgressDialog 提示信息
                        mainPDialog.setMessage(MyApplication.getInstance().getString(R.string.string_now_loading));

                        // 设置ProgressDialog 的进度条是否不明确
                        mainPDialog.setIndeterminate(false);

                        // 设置ProgressDialog 是否可以按退回按键取消
                        mainPDialog.setCancelable(false);

                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle("提示");
                        builder.setMessage("有新的版本需要更新");
                        builder.setCancelable(false);

                        InstallUtils.with(MainActivity.this)
                                .setApkUrl(url)
                                .setCallBack(new InstallUtils.DownloadCallBack() {
                                    @Override
                                    public void onStart() {
                                        mainPDialog.show();
                                        mainPDialog.setMax(100);
                                    }

                                    @Override
                                    public void onComplete(String s) {
                                        InstallUtils.installAPK(MainActivity.this, s, new InstallUtils.InstallCallBack() {
                                            @Override
                                            public void onSuccess() {
                                                //onSuccess：表示系统的安装界面被打开
                                                //防止用户取消安装，在这里可以关闭当前应用，以免出现安装被取消
//                                    Toast.makeText(context, "正在安装程序", Toast.LENGTH_SHORT).show();
                                                mainPDialog.dismiss();
                                                AppManager.getAppManager().finishAllActivity();
                                            }

                                            @Override
                                            public void onFail(Exception e) {
                                                //安装出现异常，这里可以提示用用去用浏览器下载安装
                                                mainPDialog.dismiss();
                                                AppManager.getAppManager().finishAllActivity();
                                            }
                                        });
                                    }

                                    @Override
                                    public void onLoading(long l, long l1) {
                                        int i = (int) (l1 / (l / 100));
                                        if (mainPrs != i) {
                                            mainPrs = i;
                                            mainPDialog.setProgress(mainPrs);
                                        }
                                    }

                                    @Override
                                    public void onFail(Exception e) {
                                        mainPDialog.cancel();
                                    }

                                    @Override
                                    public void cancle() {
                                        mainPDialog.cancel();
                                    }
                                })
                                .startDownload();
                    }
                });
            }
        }
    }
}
